#include "Key.h"
uint16_t key_press_time[4];
key_state_t key_state[4];
uint16_t key_index[4] = { KEY1, KEY2, KEY3, KEY4 };
uint8_t page_num = 0;
void Key_Init(void)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);		//开启GPIOB的时钟
    // 初始化四个按键方便控制UI界面
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Pin = KEY1 | KEY2 | KEY3 | KEY4;
    GPIO_Init(KEY_PORT, &GPIO_InitStructure);
}
void Key_Scan(void)
{
    uint8_t i = 0;
    for (i = 0;i < 4;i++)
    {

        if (0 == GPIO_ReadInputDataBit(KEY_PORT, key_index[i]))
        {
            key_press_time[i]++;
            //10ms一次轮询，大概1s就可以算长按了
            if (1000 <= key_press_time[i])
            {
                key_state[i] = KEY_LONG_PRESS;
            }

        }
        else
        {

            if ((KEY_LONG_PRESS != key_state[i]) && (10 <= key_press_time[i]))
            {
                key_state[i] = KEY_SHORT_PRESS;
            }
            else
            {
                key_state[i] = KEY_RELEASE;
            }
            key_press_time[i] = 0;


        }

    }

}
bool key_short_pass(uint16_t key_nums)
{
    if (key_state[key_nums] == KEY_SHORT_PRESS)
    {
        key_state[0] = KEY_RELEASE;
        key_state[1] = KEY_RELEASE;
        key_state[2] = KEY_RELEASE;
        key_state[3] = KEY_RELEASE;
        return true;
    }
    return false;
}
bool key_long_pass(uint16_t key_nums)
{
    if (key_state[key_nums] == KEY_LONG_PRESS)
    {
        key_state[0] = KEY_RELEASE;
        key_state[1] = KEY_RELEASE;
        key_state[2] = KEY_RELEASE;
        key_state[3] = KEY_RELEASE;
        return true;
    }
    return false;
}
void Key_control(void)
{
    Key_Scan();
    if (key_short_pass(0) || key_long_pass(0))
        // 按键1
        set_Rpm_value += 1;
    if (key_short_pass(1) || key_long_pass(1))
        set_Rpm_value -= 1;
    if (key_short_pass(2))
        page_num = 1;
    if (key_short_pass(3))
        page_num = 0;
    set_Rpm_value = set_Rpm_value > 3000 ? 3000 : set_Rpm_value;
    set_Rpm_value = set_Rpm_value < -3000 ? -3000 : set_Rpm_value;
}
